Android 动态加载sd卡的jar文件实现更新jar方法

微信图片_20181030105449.png

如何实现集成的Jar包动态更新,实现不需要更新Jar打包APK发布,就能解决线上的问题修复。
一、介绍
Android在API中给出可动态加载的有:DexClassLoader 和 PathClassLoader
DexClassLoader:可从SD卡中加载jar、apk和dex.
PathClassLoader:只能加载已经安装搭配Android系统中的apk文件。
这两个都是集成dalvik.system.BaseDexClassClassLoader,
当类加载请求,首先委派给父类去完成加载,父类加载不了,则自己再去完成加载,我们可以利用这个机制反过来,自定义TestClassLoader去加载本地Jar里接口Impl实现类(修复问题的class),如果加载不了,再请求到父类即(PathClassLoader)去加载工程里的Jar接口Impl实现类。

二、实现步骤
1、首先我们在Jar中定义好接口及实现类Impl,

public interface IJarFix {
    void print();
}
public class IJarFixImpl implements IJarFix {
    @Override
    public void print() {
        Log.e("umbrella1","print version 1.0");
    }
}

2、自定义TestClassLoader:

import dalvik.system.BaseDexClassLoader;
public class TestClassLoader extends BaseDexClassLoader {
    private Map<String, String> mExcludes = new ConcurrentHashMap<>();
 public TestClassLoader(String dexPath, File optimizedDirectory, String librarySearchPath, ClassLoader parent) {
        super(dexPath, optimizedDirectory, librarySearchPath, parent);
    }
    public void setExcludedClasses(String[] classNames) {
        mExcludes.clear();
        if (classNames != null && classNames.length > 0) {
            for (String name : classNames) {
                // ConcurrentHashMap doesn't allow null key or value
                if (name != null) {
                    mExcludes.put(name, name);
                }
            }
        }
    }
    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        Class<?> c = findLoadedClass(name);
        if(c == null){
            if (!mExcludes.containsKey(name)) {//这边目的是不要去加载接口IJarFix(这个是PatchClassLoader加载)
                try {
                    c = findClass(name);
                } catch (Exception e) {
                    // Not found within the module, continue on
                }
            }
        }
        if(c == null)
            c = getParent().loadClass(name);//父classloader
        return c;
    }
}

TestClassLoader加载本地JAR

package cn.umbrella.mylibrary;
public class Modul {
    public static final String TEMP_DEX_FILE_NAME ="IJarHotDex.jar";
    //------加载是jar包(包含classes.dex)----//
    public static ClassLoader createTestClassLoader(Context cxt){
        ClassLoader parentLoader = cxt.getClassLoader();
        File file = new File(cxt.getDir("dex",Context.MODE_PRIVATE),TEMP_DEX_FILE_NAME);
        File copyFile = getTempDexFile(cxt);
        FileUtil.copy(copyFile,file);
        File dexLib= cxt.getDir("outdex", Context.MODE_PRIVATE);
        FileUtil.ensureDir(dexLib,false);`
        TestClassLoader testClassLoader = new TestClassLoader(file.getPath(),dexLib,null,parentLoader);
        return testClassLoader;
    }
    public static File getTempDexFile(Context cxt) {
        try {
            String tempDexPath = FileUtil.getExternalStoragePath(cxt);
            String tempDexFilePath = tempDexPath + TEMP_DEX_FILE_NAME;
            Log.e("yuguohe", "tempDexFilePath:" + tempDexFilePath);
            File tempDexFileDir = new File(tempDexPath);//存放在SD卡上的临时dex文件的所在目录
            if (!tempDexFileDir.exists() || !tempDexFileDir.isDirectory()) {
                if (!tempDexFileDir.mkdirs()) {
                    return null;
                }
            }
            File tempDexFile = new File(tempDexFilePath);//存放在SD卡上的临时dex文件
            if (!tempDexFile.exists()) {
                if (!tempDexFile.createNewFile()) {
                    return null;
                }
            }
            return tempDexFile;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}

生产JAR
task makeJar(type: Copy) {
//删除存在的
delete 'build/libs'
//设置拷贝的文件
from('build/intermediates/bundles/default/')
//打进jar包后的文件目录
into('build/libs/')
//将classes.jar放入build/libs/目录下
//include ,exclude参数来设置过滤
//(我们只关心classes.jar这个文件)
include('classes.jar')
//重命名
rename ('classes.jar', 'IJarHotDex_o.jar')
}
然后在D:\android-sdk\build-tools\23.0.1\目录下使用命令 dx --dex --output=IJarHotDex_o.jar IJarHotDex.jar,IJarHotDex.jar我们所需要的二进制jar包(包含class.dex),放在后台下载下来或SD卡上。
3、实现动态加载

try {
                    JarInfFactory infFactory = JarInfFactory.getInstance();
                    infFactory.init(MainActivity.this);
                    cn.umbrella.mylibrary.IJarFix jarFix = infFactory.getIHotFix();
                    Log.e("umbrella1", "jarFix=" + jarFix + " &classLoader=" + jarFix.getClass().getClassLoader());
                    jarFix.print();
                } catch (Exception e) {
                    e.printStackTrace();
                }

JarInfFactory接口抽象工厂类:

package cn.umbrella.mylibrary;
import android.content.Context;
import android.util.Log;
public class JarInfFactory {
    private static JarInfFactory mInstance = null;
    private IJarFix mIJarFix;
    private Context mContext;
  ModulManager mModulManager;
    public static synchronized JarInfFactory getInstance() {
        if (mInstance == null) {
            mInstance = new JarInfFactory();
        }
        return mInstance;
    }

    public void setExcludedClasses(){
        String ex[] = new String[] {
                "cn.umbrealla.mylibrary.IJarFix",
        };
        if(mModulManager != null)
            mModulManager.setExcludedClasses("ssp", ex);
    }
    public IJarFix getIHotFix(){
        if(mIJarFix == null){
            mIJarFix =mModulManager.getModuleInterface("ssp",IJarFix.class,null,null,null);
        }
        return mIJarFix;
    }
    public void setInvalide(){
        if(mIJarFix != null){
            mIJarFix = null;
        }
        String ex[] = new String[] {
                "cn.umbrealla.mylibrary.IJarFix",//接口
        };
        mModulManager.setExcludedClasses("ssp", ex);
        mModulManager.addClassLoaderModuleName("ssp");
        getIHotFix();
    }
}
package cn.umbrella.mylibrary;
public class ModulManager {
    private ArrayList<ClassLoader>mClassLoaderList = new ArrayList<>();
    private Context mContext;
    public void addClassLoaderList(ClassLoader loader){
        mClassLoaderList.clear();
        mClassLoaderList.add(loader);
    }
    public ModulManager(Context cxt){
        mContext = cxt;
    }
    public <T> T getModuleInterface(String moduleName,Class<T> interfaceType,
                                    String staticMethod,
                                    Class<?>[] paramTypes, Object[] paramObjs){
        Context cxt = mContext;
        ClassLoader c1 = null;
        c1 = getClassLoaderCache();
        if(c1 == null) {
            c1 = ModulManager.class.getClassLoader();
        }
        try {
            return Util.newInstance(c1, interfaceType.getName() + "Impl", null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public void addClassLoaderModuleName(String moduleName){
        Context cxt = mContext;
        ClassLoader loader = Modul.createTestClassLoader(cxt);
        updateExcludedClasses(loader,getExcludedClasses(moduleName));
        addClassLoaderList(loader);
    }

    public ClassLoader getClassLoaderCache(){
        if(mClassLoaderList!=null && mClassLoaderList.size() > 0)
            return mClassLoaderList.get(0);
        return null;
    }
    public void updateExcludedClasses(ClassLoader cl, String[] classNames) {
        if (cl instanceof TestClassLoader) {
            ((TestClassLoader) cl).setExcludedClasses(classNames);
        }
    }
}

反射工具类:

package cn.umbrella.mylibrary;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by yuguohe on 2018-8-3.
 */

public class Util {
    public static <T> T newInstance(ClassLoader classLoader,String className,Class<?>[] paramTypes, Object[] paramObjs){
        T clT = null;
        try {
            Class<?> c = classLoader.loadClass(className);
            Constructor constructor = c.getConstructor(paramTypes);
            clT = (T)constructor.newInstance(paramObjs);
            if(clT == null)
                clT = (T)c.newInstance();
        } catch (Exception e) {
            e.printStackTrace();

        }
        return clT;
    }
}

实现本地JAR方法替代工程集成的JAR的方法:

           JarInfFactory infFactory = JarInfFactory.getInstance();
                 infFactory.setInvalide();
                    IJarFix o = infFactory.getIHotFix();
                    Log.e("umbrella1", "jarFix=" + o + " &classLoader=" + o.getClass().getClassLoader());
                    o.print();
                    Log.e("umbrella1", "o=" + o);
微信图片_20181024173206.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,227评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,755评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,899评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,257评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,617评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,757评论 1 221
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,982评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,715评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,454评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,666评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,148评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,512评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,156评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,112评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,896评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,809评论 2 279
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,691评论 2 272

推荐阅读更多精彩内容